package net.zhengxinyun.performance.service.login;

import net.zhengxinyun.performance.Util.MD5;
import net.zhengxinyun.performance.Util.TokenUtil;
import net.zhengxinyun.performance.entity.TokenEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.mapper.login.UserEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther: hyp
 * @Date: 2018/10/30 14:57
 */
@Service
public class LoginServiceImpl implements LoginService {

    private UserEntityMapper userEntityMapper;

    private TokenService tokenService;

    @Autowired
    public LoginServiceImpl(UserEntityMapper userEntityMapper, TokenService tokenService) {
        this.userEntityMapper = userEntityMapper;
        this.tokenService = tokenService;
    }

    /**
     * 登录生成token
     *
     * @param userFilter
     * @return
     */
    @Override
    public TokenEntity loginGetToken(UserFilter userFilter) throws Exception {
        String passWord = MD5.md5(userFilter.getUserPassword(),MD5.MD5_STR);
        userFilter.setUserPassword(passWord);
        List<UserFilter> list = userEntityMapper.query(userFilter);
        if (list == null || list.size() == 0) {
            return null;
        }
        UserFilter user = list.get(0);
        String token = TokenUtil.createJWT(user.getId().toString(), user.getUserName(), user.getUserPassword(), TokenUtil.OVERTIME);
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setValue(token);
        tokenEntity.setPostTime(new Date());
        tokenEntity.setUserId(user.getId());
        tokenService.deleteByUserId(user.getId());
        tokenService.insert(tokenEntity);
        return tokenEntity;
    }

    /**
     * 根据token获取用户
     *
     * @param tokenEntity
     * @return
     */
    @Override
    public UserEntity getUserByToken(TokenEntity tokenEntity) {
        TokenEntity token = tokenService.queryByValue(tokenEntity.getValue());
        if (token == null) {
            return null;
        }
        UserEntity userEntity = userEntityMapper.selectByPrimaryKey(token.getUserId());
        if (userEntity == null) {
            return null;
        }
        return userEntity;
    }

    @Override
    public void exit(TokenEntity tokenEntity) {
        tokenService.delete(tokenEntity);
    }
}
